package com.sd.repay.service.impl;

import com.sd.repay.common.Constants;
import com.sd.repay.dao.BaseDao;
import com.sd.repay.pojo.RepayPlanDetail;
import com.sd.repay.service.RepayPlanDetailService;
import com.sd.repay.service.RepayPlanService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sd
 * @Description: 还款计划明细Service
 * @date 2017年10月25日
 */
@Service
public class RepayPlanDetailServiceImpl implements RepayPlanDetailService {

    private static Logger log = LoggerFactory.getLogger(RepayPlanDetailServiceImpl.class);

    @Autowired
    private BaseDao baseDao;

    @Autowired
    private RepayPlanService planService;


    /**
     * 根据批次号获取明细
     *
     * @param batchNo
     * @return
     * @throws Exception
     */
    @Override
    public List<RepayPlanDetail> getDetailByBatchNo(String batchNo) throws Exception {

        String sql = " SELECT * FROM t_repay_plan_detail WHERE batch_no = ? ";
        return baseDao.findList(RepayPlanDetail.class, sql, batchNo);
    }

    /**
     * 根据明细编号获取明细对象
     *
     * @param planNo
     * @return
     * @throws Exception
     */
    @Override
    public RepayPlanDetail getDetailByPlanNo(String planNo) throws Exception {

        String sql = " SELECT * FROM t_repay_plan_detail WHERE plan_no = ? ";
        return baseDao.findFirst(RepayPlanDetail.class, sql, planNo);
    }

    /**
     * 获取下一个需要执行的明细
     *
     * @param batchNo
     * @return
     * @throws Exception
     */
    @Override
    public RepayPlanDetail getNextExeuteDetailByBatchNo(String batchNo) throws Exception {

        String sql = " SELECT * FROM t_repay_plan_detail WHERE batch_no = ? AND plan_status NOT IN (?, ?) AND plan_count < ? ORDER BY plan_index ASC ";
        return baseDao.findFirst(RepayPlanDetail.class, sql, new Object[]{batchNo, Constants.PLAN_DETAIL_STATUS_SUCCESS, Constants.PLAN_DETAIL_STATUS_IN_EXECUTE, Constants.PLAN_MAX_EXECUTE_COUNT});
    }

    /**
     * 获取上一条执行成功的明细
     *
     * @param batchNo
     * @param planIndex
     * @return
     * @throws Exception
     */
    @Override
    public RepayPlanDetail getPrevSuccessDetailByBatchNo(String batchNo, int planIndex) throws Exception {

        if (planIndex < 2) {
            return null;
        }
        planIndex = planIndex - 1;
        String sql = " SELECT * FROM t_repay_plan_detail WHERE batch_no = ? AND plan_index = ? AND plan_status = ?";
        return baseDao.findFirst(RepayPlanDetail.class, sql, new Object[]{batchNo, planIndex, Constants.PLAN_DETAIL_STATUS_SUCCESS});
    }

    /**
     * 根据批次号，明细状态获取计划明细
     *
     * @param batchNo
     * @param status
     * @return
     * @throws Exception
     */
    @Override
    public List<RepayPlanDetail> getDetailByBatchNoAndStatus(String batchNo, String status) throws Exception {

        String sql = " SELECT * FROM t_repay_plan_detail WHERE batch_no = ? AND plan_status = ? ";
        return baseDao.findList(RepayPlanDetail.class, sql, new Object[]{batchNo, status});
    }

    /**
     * 获取第一条明细
     *
     * @param batchNo
     * @return
     * @throws Exception
     */
    @Override
    public RepayPlanDetail getFirstDetail(String batchNo) throws Exception {

        String sql = "SELECT * FROM t_repay_plan_detail WHERE batch_no = ? AND plan_index = 1";
        return baseDao.findFirst(RepayPlanDetail.class, sql, batchNo);
    }

    /**
     * 更改明细状态
     *
     * @param planNo
     * @param newStatus
     * @param oldStatus
     * @param resMsg
     * @return
     * @throws Exception
     */
    @Override
    public int updateDetailStatus(String planNo, String newStatus, String oldStatus, String resMsg) throws Exception {

        String sql = " UPDATE t_repay_plan_detail SET plan_status = ?, res_msg = ? ";
        List<Object> params = new ArrayList<>();
        params.add(newStatus);
        params.add(resMsg);

        sql += "WHERE plan_no = ? ";
        params.add(planNo);

        if (StringUtils.isNotBlank(oldStatus)) {
            sql += " AND plan_status = ? ";
            params.add(oldStatus);
        }
        return baseDao.execute(sql, params.toArray());
    }

    /**
     * 是否是最后一笔明细
     *
     * @param batchNo
     * @param planIndex
     * @return
     * @throws Exception
     */
    @Override
    public boolean isLastIndexDetail(String batchNo, int planIndex) throws Exception {

        String sql = "SELECT id FROM t_repay_plan_detail WHERE batch_no = ? AND plan_index > ?";
        Map<String, Object> map = baseDao.findFirst(sql, new Object[]{batchNo, planIndex});
        return null == map || map.isEmpty();
    }

    @Override
    public List<RepayPlanDetail> getDetailDoingAndDone(String batchNo) throws Exception {

        String sql = " SELECT * FROM t_repay_plan_detail WHERE batch_no = ? AND (plan_status ='1' or plan_status='2' or plan_status='3') ";
        return baseDao.findList(RepayPlanDetail.class, sql, new Object[]{batchNo});
    }

    /**
     * 新增计划明细执行次数
     *
     * @param planNo
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public int incrementDetailCount(String planNo) throws Exception {
        String sql = " UPDATE t_repay_plan_detail SET plan_count = plan_count + 1 WHERE plan_no = ? ";
        return baseDao.execute(sql, planNo);
    }

    /**
     * 重置计划明细执行次数
     *
     * @param planNo
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public int resertDetailCount(String planNo) throws Exception {
        String sql = "UPDATE t_repay_plan_detail SET plan_count = 0 WHERE plan_no = ?";
        return baseDao.execute(sql, planNo);
    }

    /**
     * 统计批次明细信息
     *
     * @param batchNo
     * @param detailType
     * @param detailStatus
     * @return
     */
    @Override
    public Map<String, Object> countInfoByBatchAndTypeAndStatus(String batchNo, String detailType, String detailStatus) {
        String sql = " SELECT IFNULL(SUM(plan_amount), 0) AS sumAmount, count(*) AS countNum FROM t_repay_plan_detail WHERE batch_no = ? AND plan_type = ? AND plan_status = ? ";
        Map<String, Object> result = baseDao.findFirst(sql, new Object[]{batchNo, detailType, detailStatus});
        return (result == null || result.isEmpty()) ? new HashMap<>() : result;
    }
}
